import { useNamespace } from '@ibiz-template/vue3-util';
import { computed, defineComponent } from 'vue';
import './form-item-container.scss';

export const IBizFormItemContainer = defineComponent({
  name: 'IBizFormItemContainer',
  props: {
    required: {
      type: Boolean,
      required: true,
    },
    error: {
      type: String,
    },
    label: {
      type: String,
    },
    labelClass: {
      type: Array<string>,
    },
    labelPos: {
      type: String,
      required: true,
    },
    labelWidth: {
      type: Number,
      default: 130,
    },
  },
  setup(props) {
    const ns = useNamespace('form-item-container');

    const cssVars = computed(() => {
      if (props.labelWidth !== 130) {
        return ns.cssVarBlock({ 'label-width': `${props.labelWidth}px` });
      }
      return {};
    });
    return { ns, cssVars };
  },
  render() {
    // label内容
    const label = (
      <div
        class={[this.ns.e('label'), ...(this.labelClass || [])]}
        title={this.label}
      >
        {this.label}
      </div>
    );

    // 内容区，包含编辑器和错误消息
    const content = (
      <div
        class={[
          this.ns.e('content'),
          this.ns.em('content', `label-${this.labelPos.toLowerCase()}`),
        ]}
      >
        <div class={[this.ns.e('editor')]}>{this.$slots.default?.()}</div>
        {this.error ? (
          <div title={this.error} class={[this.ns.e('error')]}>
            {this.error}
          </div>
        ) : null}
      </div>
    );

    return (
      <div
        class={[
          this.ns.b(),
          this.ns.m(this.labelPos.toLowerCase()),
          this.ns.is('required', this.required),
          this.ns.is('error', !!this.error),
        ]}
        style={this.cssVars}
      >
        {this.labelPos === 'LEFT' || this.labelPos === 'TOP' ? label : null}
        {content}
        {this.labelPos === 'RIGHT' || this.labelPos === 'BOTTOM' ? label : null}
      </div>
    );
  },
});
